import 'package:flutter/material.dart';
import 'package:shenling_flutter/pages/login/index.dart';
import 'package:shenling_flutter/pages/mine/setting.dart';
import 'package:shenling_flutter/pages/tab_bar_page.dart';
import 'package:shenling_flutter/utils/toast.dart';
import 'package:shenling_flutter/utils/token.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatefulWidget {
  const MyApp({super.key});

  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  late Future<bool> _checkTokenFuture;

  @override
  void initState() {
    super.initState();
    // 初始化检查 token
    _checkTokenFuture = _checkUserLogin();
  }

  Future<bool> _checkUserLogin() async {
    await TokenManager().init();
    final tokenManager = TokenManager();
    final token = tokenManager.getToken() ?? '';
    return token.isNotEmpty; // 返回用户是否已登录
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      routes: {
        '/': (context) => FutureBuilder<bool>(
              future: _checkTokenFuture,
              builder: (context, snapshot) {
                // 处理异步结果
                if (snapshot.connectionState == ConnectionState.waiting) {
                  return const Center(child: CircularProgressIndicator());
                } else if (snapshot.hasError || !snapshot.data!) {
                  return const LoginPage(); // 未登录
                } else {
                  return const TabBarPage(); // 已登录
                }
              },
            ),
        '/login': (context) => const LoginPage(),
        '/home': (context) => const TabBarPage(),
        '/setting': (context) => const SettingPage(),
      },
      onGenerateRoute: (settings) {
        if (settings.name != '/' && settings.name != '/login') {
          // 保证未登录的情况下无法访问其他页面
          return MaterialPageRoute(builder: (context) => const LoginPage());
        }
        return null;
      },
      initialRoute: '/',
    );
  }
}
